<!--
 * @Author: Olivia
 * @Date: 2022-08-23 21:37:11
 * @custom_string_Olivia: Less is more
-->
<template>
 <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
        <van-search
            v-model="searchText"
            show-action
            placeholder="请输入搜索关键词"
            background="#3296fa"
            @search="onSearch"
            @cancel="onCancel"
            @focus="isResultShow=false "
        />
    </form>
    <!-- 搜索栏 -->
    <!-- 搜索结果 -->
    <search-result
        v-if="isResultShow"
        :search-text="searchText"
    />
    <!-- 搜索结果 -->
     <!-- 联想建议 -->
    <search-suggestion
    :search-text="searchText"
    @search="onSearch"
    v-else-if="searchText"/>
    <!-- 联想建议 -->
    <!-- 搜搜历史 -->
    <search-history
        v-else
        :searchHistories = "searchHistories"
        @clear-search-history = "searchHistories = []"
        @search = "onSearch"
        />
    <!-- 搜搜历史 -->
 </div>
</template>
<script>
import searchHistory from './components/search-history.vue'
import searchSuggestion from './components/search-suggestion.vue'
import searchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'search',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TT_TT_HISTORIES') || []

    }
  },
  created () {
  },
  watch: {
    searchHistories (val) {
      setItem('TT_HISTORIES', val)
    }
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  computed: {
  },
  methods: {
    onSearch (value) {
      // 更新文本框内容
      this.searchText = value
      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(value)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(value)
      this.isResultShow = true
      console.log({ value }, JSON.stringify(value))
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>
<style lang='less'  scoped>
    .search-container{
        .van-search__action{
            color: #fff;
        }
    }
</style>
